<template>
    <fieldset>
        <legend>商品</legend>
        <ul>
            <li v-for="item in productData" :key="item.id">
                名称：{{ item.title }}-------
                价格：{{ item.price }}-------
                库存: {{ item.inventory }}-------
                <button @click="addProduct(item)" :disabled="item.inventory===0">添加</button>
            </li>
        </ul>
    </fieldset>
</template>

<script setup>
import { useProduct } from '../../store/product';
import { storeToRefs } from 'pinia'
import { useCart } from '../../store/cart'

let cartStore = useCart()
let { cartData } = storeToRefs(cartStore)

let productStore = useProduct()

let { productData } = storeToRefs(productStore)

productStore.fetch_data()

let addProduct = (item) => {
    let obj = {
        id: item.id,
        title: item.title,
        count: 1,
        price: item.price
    }
    let target = productData.value.find(i => 
        i.id == item.id
    )
    console.log(target);
    target.inventory--

    let target2=cartData.value.find(i=>i.id==item.id)

    if(!target2){
        cartData.value.push(obj)
    }else{
        target2.count++
    }
}
</script>